'use strict'

// 对于electron来说,background.js就是主进程.

// electron启动时的脚本文件.
import {app, protocol, BrowserWindow, ipcMain} from 'electron'
// import {app, protocol, BrowserWindow, ipcMain,Tray} from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'
import installExtension, {VUEJS3_DEVTOOLS} from 'electron-devtools-installer'
// import {createMainWindow} from "./winpage/mainwin"
import {request} from './util/httprequest'
import * as electron from "electron";

const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    {scheme: 'app', privileges: {secure: true, standard: true}}
])

let win

let tray

let login_account_string = ""

// async 异步.
async function createWindow() {
    // Create the browser window.
    const Menu = electron.Menu
    // 渲染进程.
    win = new BrowserWindow({
        width: 1400,
        height: 900,
        title: "简聊",
        resizable: false,
        frame: false,
        webPreferences: {
            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
            contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
            webSecurity: false
        }
    })

    // 开启调试.
    // win.webContents.openDevTools()
    // win.once('focus',()=>win.flashFrame(false))
    // 设置菜单导航栏为nil.
    Menu.setApplicationMenu(null)

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        // await 暂停diamante在该行上，知道promise完成，然后返回结果，再继续执行await。
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        // 在Windows窗口加载html文件,而html文件的渲染由Vue来进行渲染.
        win.loadURL('app://./index.html')
    }
}

async function createAddWindow() {
    // Create the browser window.
    const Menu = electron.Menu
    // 渲染进程.
    const win = new BrowserWindow({
        width: 1400,
        height: 900,
        title: "简聊",
        resizable: false,
        // frame: false,
        webPreferences: {
            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
            contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
            webSecurity: false
        }
    })

    // 设置菜单导航栏为nil.
    Menu.setApplicationMenu(null)

    // 突出显示.
    // win.once()

    // win.once('focus',()=>win.flashFrame(false))
    win.flashFrame(true)

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        // await 暂停diamante在该行上，知道promise完成，然后返回结果，再继续执行await。
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        // createProtocol('app')
        // 在Windows窗口加载html文件,而html文件的渲染由Vue来进行渲染.
        // 新的HTML文件.
        win.loadURL('app://./add.html')
    }
}

ipcMain.on('newWindows', (event, arg) => {
    // TODO: 开启一个新的窗口,暂时不进行修改.
    // arg 是我们自己进行传送的参数.
    // console.log("arg: ", arg)
    // console.log("event: ", event)
    // createAddWindow()
})

ipcMain.on('flashFrame', (event, arg) => {
    // for循环搞定.
    win.once('focus', () => win.flashFrame(false))
    win.flashFrame(true)
})

// 需要.
ipcMain.on('login_suc', (event, args) => {
    login_account_string = args
})

ipcMain.on('windowCustomClose', (event, args) => {
    // 程序退出.
    // app.quit()
    app.exit()
})

ipcMain.on('windowNarrow', (eventt, args) => {
    win.minimize()
})

// app.quit()：调用会先触发app的before-quit事件，然后再触发所有窗口的关闭事件，
// 窗口全部关闭了（调用app.quit()关闭窗口是不会触发window-all-closed的，会触发will-quit），
// 触发app的quit事件。但是如果在quit事件前使用event.preventDefault()阻止了默认行为（win的close事件，app的before-quit和will-quit），
// 软件还是不会关闭。
// app.exit()：很好理解，最粗暴的强制关闭所有窗口，触发app的quit事件，故win的close事件，app的before-quit和will-quit不会被触发

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        // 向渲染进程通信.
        // win 已经被销毁了.
        // 想来想去这里必须的在此重新下线一次.
        if (login_account_string !== "") {
            request("get", "/user/offline?login_account_string=" + login_account_string)
        }
        app.quit()
    }
})

// 主进程向渲染进程发送消息.
// app.on('before-quit', () => {
// win.webContents.send('off_line', login_account_string)
// })

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {

    // if (isDevelopment && !process.env.IS_TEST) {
    //     // Install Vue Devtools
    //     try {
    //         await installExtension(VUEJS3_DEVTOOLS)
    //     } catch (e) {
    //         console.error('Vue Devtools failed to install:', e.toString())
    //     }
    // }

    // tray = new Tray("app://./chart_photo_32.jpg")
    // 右键菜单列表先不进行显示.

    // tray.setToolTip("IM")

    // 创建Win窗口.
    createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}